<template>
  <div class="system-logs">
    <div class="page-header">
      <h2>系统日志</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleExport" :loading="exportLoading">
          <el-icon>
            <Download />
          </el-icon>
          导出日志
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-form-item label="操作用户">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名" 
            clearable 
            @keyup.enter="handleSearch"
            @clear="handleReset"
          />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select 
            v-model="searchForm.module" 
            placeholder="请选择模块" 
            clearable 
            class="module-select"
            @change="updateActionOptions"
          >
            <el-option v-for="item in moduleList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="操作类型">
          <el-select v-model="searchForm.action" placeholder="请选择类型" clearable class="module-select">
            <el-option v-for="item in actionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker 
            v-model="searchForm.dateRange" 
            type="datetimerange" 
            range-separator="至"
            start-placeholder="开始时间" 
            end-placeholder="结束时间" 
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 日志表格 -->
    <div class="table-container">
      <el-table :data="displayData" v-loading="loading" border stripe>
        <el-table-column prop="id" label="ID" mix-width="100" />
        <el-table-column prop="userId" label="操作用户Id" mix-width="100" />
        <el-table-column label="操作用户" mix-width="100">
          <template #default="{ row }">
            <el-tag type="primary" size="small">
              {{ row.username }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="action" label="操作类型" mix-width="200">
          <template #default="{ row }">
            <el-tag type="warning" size="small">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作模块" mix-width="150">
          <template #default="{ row }">
            <el-tag type="primary" size="small">
              {{ getModuleText(row.resource) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" mix-width="100">
          <template #default="scope">
<el-tag :type="scope.row.isSuccess ? 'success' : 'danger'" size="small">
      {{ scope.row.isSuccess ? "成功" : "失败" }}
    </el-tag>

          </template>
        </el-table-column>
        <el-table-column label="操作时间" mix-width="200">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination :current-page="pagination.page" :page-size="pagination.pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Download } from '@element-plus/icons-vue'
import { useLogStore } from '@/stores/log'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const tableData = ref([])
const displayData = ref([])
const useStore = useLogStore()
const isSearching = ref(false) // 跟踪是否正在搜索状态
const currentSearchForm = ref({}) // 当前搜索条件
// 搜索表单
const searchForm = reactive({
  username: '',
  module: '',
  action: '',
  dateRange: []
})

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})
const moduleList = ref([
  { label: '用户管理', value: 'Users' },
  { label: '角色管理', value: 'Roles' },
  { label: '菜单管理', value: 'Menus' },
  { label: '系统配置', value: 'SystemConfigs' },
  { label: '日志管理', value: 'OperationLogs' },
  { label: '文件管理', value: 'Files' },
  { label: '认证', value: 'auth' },
  { label: '文章管理', value: 'Articles' },
  { label: '文章分类管理', value: 'ArticleCategories' },
  { label: '系统设置', value: 'System' },
])
// 方法
const getModuleText = (module) => {
  const moduleMap = {
    'Users': '用户管理',
    'Roles': '角色管理',
    'Menus': '菜单管理',
    'System': '系统设置',
    'auth': '认证',
    'OperationLogs': '日志管理',
    'Files': '文件管理',
    'Articles': '文章管理',
    'ArticleCategories': '文章分类管理',
    'SystemConfigs': '系统配置',
    'system_configs':'系统设置',
    'Auth':'认证'
  };
  return moduleMap[module] || module;
};

const getActionText = (action) => {
  const actionMap = {
    'operationlogs.search': '获取日志',
    'operationlogs.create': '日志创建',
    'operationlogs.update': '日志更新',
    'operationlogs.exportcsv': '日志导出',
    'users.getusers': '获取用户列表',
    'users.createuser': '创建用户',
    'users.updateuser': '更新用户',
    'users.deleteuser': '删除用户',
    'users.updateprofile ': '更新个人信息',
    'users.changepassword': '修改密码',
    'auth.login': '用户登录',
    'auth.logout': '用户登出',
    'auth.register': '用户注册',
    'auth.refreshtoken': '令牌刷新',
    'roles.getroles': '获取角色列表',
    'roles.createrole': '创建角色',
    'roles.updaterole': '更新角色',
    'roles.getrole':'获取单个角色',
    'roles.deleterole': '删除角色',
    'menus.getmenus': '获取菜单列表',
    'menus.createmenu': '创建菜单',
    'menus.updatemenu': '更新菜单',
    'menus.deletemenu': '删除菜单',
    'menus.getmenutree': '获取菜单树',
    'settings.getsettings': '获取系统设置',
    'systemconfigs.getall': '获取系统配置',
    'SystemConfig.BatchUpdate': '系统配置批量更新',
    'systemconfigs.batchupdate': '系统配置批量更新',
    'users.resetpasswordself': '用户重置密码',
    'auth.getprofile': '获取用户信息',
    'files.getmyfiles': '获取文件',
    'files.upload': '上传文件',
    'files.download': '下载文件',
    'files.deletefile': '删除文件',
    'files.search': '文件搜索',
    'exception': '出错了',
    'articles.getarticles': '获取文章列表',
    'articlecategories.update': '更新类名',
    'articlecategories.create': '创建类名',
    'articlecategories.delete': '删除类名',
    'articlecategories.getall': '获取文章类别',
    'articles.updatearticle': '更新文章',
    'articles.createarticle': '创建文章',
    'articles.deletearticle': '删除文章',
    'articles.getarticle': '查看文章',

  }
  return actionMap[action] || action
}
const moduleActionMap = ref({
  'auth': [
    { label: '登录', value: 'auth.login' },
    { label: '登出', value: 'auth.logout' },
    { label: '注册', value: 'auth.register' },
    { label: '令牌刷新', value: 'auth.refreshtoken' },
    { label: '获取用户信息', value: 'auth.getprofile' }
  ],
  'Users': [
    { label: '获取用户列表', value: 'users.getusers' },
    { label: '新增用户', value: 'users.createuser' },
    { label: '更新用户', value: 'users.updateuser' },
    { label: '删除用户', value: 'users.deleteuser' },
    { label: '更新个人信息', value: 'users.updateprofile' },
    { label: '修改密码', value: 'users.changepassword' }
  ],
  'Roles': [
    { label: '获取角色列表', value: 'roles.getroles' },
    { label: '新增角色', value: 'roles.createrole' },
    { label: '更新角色', value: 'roles.updaterole' },
    { label: '删除角色', value: 'roles.deleterole' }
  ],
  'Menus': [
    { label: '获取菜单列表', value: 'menus.getmenus' },
    { label: '新增菜单', value: 'menus.createmenu' },
    { label: '更新菜单', value: 'menus.updatemenu' },
    { label: '删除菜单', value: 'menus.deletemenu' },
    { label: '获取菜单树', value: 'menus.getmenutree' }
  ],
  'Files': [
    { label: '获取文件', value: 'files.getmyfiles' },
    { label: '上传文件', value: 'files.upload' },
    { label: '下载文件', value: 'files.download' },
    { label: '删除文件', value: 'files.deletefile' },
    { label: '文件搜索', value: 'files.search' }
  ],
  'SystemConfigs': [
    { label: '获取系统设置', value: 'settings.getsettings' },
    { label: '获取系统配置', value: 'systemconfigs.getall' },
    { label: '系统配置批量更新', value: 'SystemConfig.BatchUpdate' },
    { label: '系统配置批量更新', value: 'SystemConfig.BatchUpdate' }
  ],
  'OperationLogs': [
    { label: '获取日志', value: 'operationlogs.search' },
    { label: '日志更新', value: 'operationlogs.update' },
    { label: '日志导出', value: 'operationlogs.exportcsv' }
  ],
  'Articles': [
    { label: '获取文章列表', value: 'articles.getarticles' },
    { label: '更新文章', value: 'articles.updatearticle' },
    { label: '创建文章', value: 'articles.createarticle' },
    { label: '删除文章', value: 'articles.deletearticle' },
    { label: '查看文章', value: 'articles.getarticle' }
  ],
  'ArticleCategories': [
    { label: '获取文章类别', value: 'articlecategories.getall' },
    { label: '创建类名', value: 'articlecategories.create' },
    { label: '删除类名', value: 'articlecategories.delete' },
    { label: '更新类名', value: 'articlecategories.update' },
  ]
});

const actionOptions = computed(() => {
  if (!searchForm.module) {
    return [];
  }
  return moduleActionMap.value[searchForm.module] || [];
});

const updateActionOptions = () => {
  searchForm.action = null; // 清空操作类型
};

const loadData = async () => {
  loading.value = true;
  try {
    let response;
    if (isSearching.value) {
      // 如果正在搜索状态，使用搜索API
      response = await useStore.searchLogs(currentSearchForm.value, {
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      });
    } else {
      // 否则使用普通获取API
      response = await useStore.getLogs();
      console.log(response);
      
    }

    // 检查后端返回的数据是否正确
    if (response) {
      tableData.value = response.logs;
      displayData.value = [...tableData.value]
      pagination.value = response.pagination;
    } else {
      throw new Error('后端返回数据格式不正确');
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = async () => {
  try {
    loading.value = true;
    isSearching.value = true;
    currentSearchForm.value = { ...searchForm };
    pagination.value.page = 1; // 重置到第一页
    
    const response = await useStore.searchLogs(searchForm, {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    });
    
    if (response) {
      tableData.value = response.logs;
      displayData.value = [...tableData.value];
      pagination.value = response.pagination;
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    module: '',
    action: '',
    dateRange: []
  });
  isSearching.value = false;
  currentSearchForm.value = {};
  pagination.value.page = 1;
  loadData();
};

const handleExport = async () => {
  try {
    exportLoading.value = true
    ElMessage.info('正在导出日志...')
    
    // 构建导出参数（不包含分页，导出所有数据）
    const exportParams = new URLSearchParams()
    
    if (searchForm.username) exportParams.append('username', searchForm.username)
    if (searchForm.action) exportParams.append('action', searchForm.action) 
    if (searchForm.module) exportParams.append('resource', searchForm.module)
    if (searchForm.dateRange?.[0]) exportParams.append('start', searchForm.dateRange[0])
    if (searchForm.dateRange?.[1]) exportParams.append('end', searchForm.dateRange[1])
    
    // 直接下载文件
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    const url = `/operation-logs/export?${exportParams.toString()}`
    
    // 使用XMLHttpRequest处理带认证的文件下载
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    xhr.responseType = 'blob'
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        const blob = new Blob([xhr.response], { type: 'text/csv' })
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.setAttribute('download', `操作日志_${new Date().toISOString().slice(0, 10)}.csv`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        ElMessage.success('日志导出成功')
      } else {
        ElMessage.error('日志导出失败')
      }
      exportLoading.value = false
    }
    
    xhr.onerror = function() {
      ElMessage.error('日志导出失败')
      exportLoading.value = false
    }
    
    xhr.send()
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('日志导出失败')
    exportLoading.value = false
  }
}
//格式化日期
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.page = 1
  loadData()
}

const handlePageChange = (val) => {
  pagination.value.page = val
  loadData()
}

// 生命周期
onMounted(() => {
  loadData();
})
</script>

<style scoped>
.system-logs {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.log-detail {
  max-height: 500px;
  overflow-y: auto;
}

.json-data {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.module-select {
  width: 120px;
}

.error-message {
  color: #f56c6c;
  background: #fef0f0;
  padding: 10px;
  border-radius: 4px;
  border-left: 4px solid #f56c6c;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

:deep(.el-date-editor) {
  width: 350px;
}
</style>
